package com.jiang.jixiang.ui;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.huawei.hms.hmsscankit.OnResultCallback;
import com.huawei.hms.hmsscankit.RemoteView;
import com.huawei.hms.ml.scan.HmsScan;
import com.jiang.jixiang.R;
import com.jiang.jixiang.databinding.ActivityScanBinding;
import com.jiang.jixiang.dialog.InputDialog;
import com.jiang.jixiang.tools.UrlParse;
import com.ws.universal.tools.BeepManager;
import com.ws.universal.tools.base.BaseActivity;
import com.ws.universal.tools.base.ManageActivity;
import com.ws.universal.tools.eventbus.BaseBusData;
import com.ws.universal.tools.eventbus.BusCode;
import com.ws.universal.tools.eventbus.EventBusUtil;
import com.ws.universal.tools.utils.LogcatUtils;
import com.ws.universal.tools.utils.ToastUtils;

import java.util.Map;

/**
 * 扫描界面
 */
public class ScanActivity extends BaseActivity {
    // 当前Demo扫码框的宽高是300dp。
    final int SCAN_FRAME_SIZE = 246;
    int mScreenWidth;
    int mScreenHeight;
    private ActivityScanBinding binding;
    private RemoteView remoteView;
    private BeepManager beepManager;
    private Intent intent;
    private int scanType;
    private InputDialog inputDialog;
    private Bundle bundle;

    @Override
    protected void initCreate(Bundle savedInstanceState) {

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        ManageActivity.putActivity(this.getClass().getSimpleName(), this);
        binding = ActivityScanBinding.inflate(getLayoutInflater());

        setContentView(binding.getRoot());
        intent = getIntent();
        scanType = intent.getIntExtra("scanType", 1);
        // 设置扫码识别区域，您可以按照需求调整参数。
        DisplayMetrics dm = getResources().getDisplayMetrics();
        float density = dm.density;
        mScreenWidth = getResources().getDisplayMetrics().widthPixels;
        mScreenHeight = getResources().getDisplayMetrics().heightPixels;
        int scanFrameSize = (int) (SCAN_FRAME_SIZE * density);
        Rect rect = new Rect();
        rect.left = mScreenWidth / 2 - scanFrameSize / 2;
        rect.right = mScreenWidth / 2 + scanFrameSize / 2;
        rect.top = mScreenHeight / 2 - scanFrameSize / 2;
        rect.bottom = mScreenHeight / 2 + scanFrameSize / 2;
        //初始化RemoteView，并通过如下方法设置参数:setContext()（必选）传入context、
        // setBoundingBox()设置扫描区域、
        // setFormat()设置识别码制式，
        // 通过setContinuouslyScan（可选）方法设置非连续扫码模式。
        remoteView = new RemoteView.Builder().setContext(this).setBoundingBox(rect).setContinuouslyScan(false)
                //.setFormat(HmsScan.QRCODE_SCAN_TYPE, HmsScan.DATAMATRIX_SCAN_TYPE)
                .build();

        remoteView.onCreate(savedInstanceState);
        // 将自定义view加载到activity的frameLayout中。
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        binding.rim.addView(remoteView, params);

//        if (scanType == 2) {
//            binding.llManual.setVisibility(View.GONE);
//        }

        inputDialog = new InputDialog(getContext());
        inputDialog.setBtnListener(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int i) {
                if (TextUtils.isEmpty(inputDialog.getInput())) {
                    ToastUtils.showShort(getString(R.string.device_code_cannot_be_empty));
                    return;
                }
                dialog.dismiss();
                if (scanType == 2) {
                    BaseBusData baseBusData = new BaseBusData(BusCode.inputDeviceNum, inputDialog.getInput());
                    EventBusUtil.postEvent(baseBusData);
                    finish();
                } else {
                    doResult(inputDialog.getInput());
                }


            }
        });
        //inputDialog.setCanceledOnTouchOutside(true);

    }

    private void doResult(String device_code) {
        remoteView.onPause();
        beepManager.close();
        bundle = new Bundle();
        bundle.putString("device_code", device_code);
        pageJump(ScanResultActivity.class, bundle);
        finish();
    }

    @Override
    protected void initView() {
        //binding.tvScanHint.
        beepManager = new BeepManager(this);
        // 识别结果回调事件订阅
        remoteView.setOnResultCallback(new OnResultCallback() {
            @Override
            public void onResult(HmsScan[] result) {

                beepManager.playBeepSoundAndVibrate(1);
                //remoteView.onPause();
                if (result != null && result.length > 0 && result[0] != null && !TextUtils.isEmpty(result[0].getOriginalValue())) {


                    LogcatUtils.i(" setStation result " + result[0].getOriginalValue());
                    setStation(result[0].getOriginalValue());
                }
            }
        });

        binding.titleLeftBtn.setOnClickListener(view -> {

            onBackPressed();
        });

        binding.flushBtn.setOnClickListener(view -> {
            setFlashOperation();
        });
    }

    @Override
    protected void FinishDesTroy() {
        ManageActivity.removeActivity(this.getClass().getSimpleName());
    }


    //开始扫码
    private void setStation(String barCode) {
        LogcatUtils.e(" setStation 执行 " + barCode);
        Map<String, String> urlParams = UrlParse.getUrlParams(barCode);
        if (scanType == 1) {
            if (barCode.indexOf("&sn=") > -1) {
                //获得url参数
                doResult(urlParams.get("sn"));
            } else {
                finish();
                //ToastUtils.showShort(getText(R.string.qr_code_abnormal));
                Toast.makeText(getContext(), getText(R.string.qr_code_abnormal), Toast.LENGTH_LONG).show();
            }

        } else {
            Intent intent = new Intent();
            if (barCode.indexOf("&sn=?") > -1) {

                intent.putExtra("resultScanCode", urlParams.get("sn"));

            } else {
                intent.putExtra("resultScanCode", "");
                Toast.makeText(getContext(), getText(R.string.qr_code_abnormal), Toast.LENGTH_LONG).show();
            }
            setResult(Activity.RESULT_OK, intent);
            finish();
        }


        //
    }

    //控制闪关灯
    private void setFlashOperation() {
        binding.flushBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (remoteView.getLightStatus()) {
                    remoteView.switchLight();
                    binding.flushImg.setImageResource(R.mipmap.icon_flash);
                } else {
                    remoteView.switchLight();
                    binding.flushImg.setImageResource(R.mipmap.icon_flash);
                }
            }
        });
    }


    @Override
    protected void onStart() {
        super.onStart();
        remoteView.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        remoteView.onResume();
        beepManager.updatePrefs();
    }

    @Override
    protected void onPause() {
        super.onPause();
        remoteView.onPause();
        beepManager.close();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        remoteView.onDestroy();
    }

    @Override
    protected void onStop() {
        super.onStop();
        remoteView.onStop();
    }
}
